package com.mall.controller.backend;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.google.common.collect.Maps;
import com.mall.common.Const;
import com.mall.common.MySessionContext;
import com.mall.common.ResponseCode;
import com.mall.common.ServerResponse;
import com.mall.pojo.Product;
import com.mall.pojo.User;
import com.mall.service.IFileService;
import com.mall.service.IProductService;
import com.mall.service.IUserService;
import com.mall.util.PropertiesUtil;
import com.mall.vo.ProductDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by xiaoyao on 2017/8/24.
 */
@Controller
@RequestMapping("/manage/product/")
public class ProductManagerController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IProductService iProductService;

    @Autowired
    private IFileService iFileService;
    /**
     * 添加或者更新产品时保存
     * 传参的时候，传递id,就是更新商品；
     * 不传递id,就是添加商品；
     * @param product
     * @return
     */
    @RequestMapping("save.do")
    @ResponseBody
    public ServerResponse<Product> saveProduct(Product product){
        System.out.println("------添加商品传递的参数------"+product.getName());
        //判断是否登录
        if(Const.sessionId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请先登录");
        }
        HttpSession session = MySessionContext.getSession(Const.sessionId );
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(iUserService.checkAdminRole(user).isSuccess()){
            return iProductService.addAndUpdateProduct(product);
        }
        return ServerResponse.createByErrorMessage("无权限操作，需要管理员权限");
    }

    /**
     * 修改商品上下架的状态
     * @param product
     * @return
     */
    @RequestMapping("setSaleStatus.do")
    @ResponseBody
    public ServerResponse<String> setSaleStatus(Product product){
        //判断是否登录
        if(Const.sessionId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请先登录");
        }
        HttpSession session = MySessionContext.getSession(Const.sessionId );
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(iUserService.checkAdminRole(user).isSuccess()){
            return iProductService.setSaleStatus(product.getId(),product.getStatus());
        }
        return ServerResponse.createByErrorMessage("无权限操作，需要管理员权限");
    }

    /**
     * 获取产品详情
     * @param product
     * @return
     */
    @RequestMapping("detail.do")
    @ResponseBody
    public ServerResponse<ProductDetailVo> getDetail(Product product){
        //判断是否登录
        if(Const.sessionId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请先登录");
        }
        HttpSession session = MySessionContext.getSession(Const.sessionId );
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(iUserService.checkAdminRole(user).isSuccess()){
            return iProductService.manageProductDetail(product.getId());
        }
        return ServerResponse.createByErrorMessage("无权限操作，需要管理员权限");
    }

    /**
     * 产品列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("getList.do")
    @ResponseBody
    public ServerResponse<PageInfo> getList( @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        System.out.println("------获取产品列表被执行------");
        //判断是否登录
        if(Const.sessionId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请先登录");
        }
        HttpSession session = MySessionContext.getSession(Const.sessionId );
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(iUserService.checkAdminRole(user).isSuccess()){
            return iProductService.getProductList(pageNum,pageSize);
        }
        return ServerResponse.createByErrorMessage("无权限操作，需要管理员权限");
    }

    /**
     * 产品搜索
     * @param productName
     * @param productId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("search.do")
    @ResponseBody
    public ServerResponse<PageInfo> productSearch(String productName,Integer productId ,@RequestParam(value = "pageNum",defaultValue = "1") int pageNum, @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        //判断是否登录
        if(Const.sessionId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请先登录");
        }
        HttpSession session = MySessionContext.getSession(Const.sessionId );
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(iUserService.checkAdminRole(user).isSuccess()){
            return iProductService.searchProduct(productName,productId,pageNum,pageSize);
        }
        return ServerResponse.createByErrorMessage("无权限操作，需要管理员权限");
    }


    /**
     * 文件（图片）上传，ftp服务器的富文本上传
     * @param file
     * @return
     * spring mvc的文件上传 MultipartFile
     * 根据上下文动态创建相对路径
     */
    @RequestMapping("upload.do")
    @ResponseBody
    public ServerResponse upload(@RequestParam(value = "file",required = false) MultipartFile file, HttpServletRequest request){
        System.out.println("---------上传文件controller参数file=----------"+file);
        //判断是否登录
        if(Const.sessionId == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录，请先登录");
        }
        HttpSession session = MySessionContext.getSession(Const.sessionId );
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if(iUserService.checkAdminRole(user).isSuccess()){
            String path = request.getSession().getServletContext().getRealPath("upload");
            System.out.println("---------controller获取path=----------"+path);
            String targetFileName = iFileService.upload(file,path);
            //组装路径
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
            //组装返回值
            Map fileMap = Maps.newHashMap();
            fileMap.put("uri",targetFileName);
            fileMap.put("url",url);
            return ServerResponse.createBySuccess(fileMap);
        }else {
            return ServerResponse.createByErrorMessage("无权限操作，需要管理员权限");
        }
    }

    /**
     * 符文本图片上传
     * @param response
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("richtextImgUpload.do")
    @ResponseBody
    public Map richtextImgUpload(HttpServletResponse response,@RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request){
        Map resultMap = Maps.newHashMap();
        //判断是否登录
        if(Const.sessionId == null){
            resultMap.put("success",false);
            resultMap.put("msg","请登录管理员");
            return resultMap;
        }
        HttpSession session = MySessionContext.getSession(Const.sessionId );
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        //富文本中返回值有要求，这里使用simditor;可参考官网simditor.tower.im
        if(iUserService.checkAdminRole(user).isSuccess()){
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file,path);
            //组装路径
            if(StringUtil.isEmpty(targetFileName)){
                resultMap.put("success",false);
                resultMap.put("msg","上传失败");
                return resultMap;
            }
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
            resultMap.put("success",true);
            resultMap.put("msg","上传成功");
            resultMap.put("file_path",url);
            response.addHeader("Access-Control-Allow-Headers","x-File-Name");
            return resultMap;
        }else {
            resultMap.put("success",false);
            resultMap.put("msg","无权限操作，需要管理员权限");
            return resultMap;
        }
    }


}
